package dao;
import java.sql.*;  
import vo.Vote;
import java.util.ArrayList;
public class VoteDao {
	private Connection conn=null;
	public void initConnection()throws Exception{
		String driverClass="com.mysql.jdbc.Driver";
	    String url="jdbc:mysql://localhost:3306/vote?useSSL=false";
	    String user="root";
	    String password="womenilu2580";
	    Class.forName(driverClass);
	    conn=DriverManager.getConnection(url,user,password);	   
	}
	
	//返回所有教师及其得票数
	public ArrayList getAllVotes() throws Exception{
		ArrayList al=new ArrayList();
		initConnection();
		String sql="SELECT TNO,TNAME,VOTE FROM T_VOTE";
		Statement stat=conn.createStatement();
		ResultSet rs=stat.executeQuery(sql);
		while(rs.next()){
			Vote vote=new Vote();
			vote.setTeacherno(rs.getString("TNO"));
			vote.setTeachername(rs.getString("TNAME"));
			vote.setVotenumber(rs.getString("VOTE"));
			al.add(vote);
		}
		closeConnection();
		return al;		
	}
	
	//修改某些教师的得票数
	public void updateVotes(String[] teacherno)throws Exception{
		initConnection();
		String sql="UPDATE T_VOTE SET VOTE=VOTE+1 WHERE TNO=?";
		PreparedStatement ps=conn.prepareStatement(sql);
		for(int i=0;i<teacherno.length;i++)
		{
			ps.setString(1, teacherno[i]);
			ps.executeUpdate();
		}
		closeConnection();
	}
	
	public void closeConnection()throws Exception{
		conn.close();
		
	}
}
